﻿using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace Icms.WebUI.Controllers
{
    [Authorize]
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var court = Globals.Court();
            if (court != null)
            {
                //ViewBag.ConfigId = cr.Where(o => o.CourtId == court.Id).Single().Id;
            }
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Pd()
        {
            //prepare output stream
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
            Response.Buffer = true;
            Response.Clear();
            //Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.End();

            return new FileStreamResult(Response.OutputStream, "application/pdf");
        }
    }

    public interface IPdf
    {
        FileStreamResult Make(string s);
    }

    public class Pdf : IPdf
    {
        public FileStreamResult Make(string s)
        {
            using (var ms = new MemoryStream())
            {
                using (var document = new Document())
                {
                    PdfWriter.GetInstance(document, ms);
                    document.Open();
                    using (var str = new StringReader(s))
                    {
                        var htmlWorker = new HTMLWorker(document);

                        htmlWorker.Parse(str);
                    }
                    document.Close();
                }

                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                HttpContext.Current.Response.OutputStream.Flush();
                HttpContext.Current.Response.End();

                return new FileStreamResult(HttpContext.Current.Response.OutputStream, "application/pdf");
            }
        }
    }
}
